import emotionData from '../emoji'; //表情
import Clipboard from 'clipboard';

/**
 * 获取对象下的字段值
 * @param record {}
 * @param key 'a.b.c'
 * @param defaultValue
 * @returns
 */
export const getValueByKeys = (record: any = {}, key: string, defaultValue?: unknown): any => {
  const keys = key.split('.');
  for (let i = 0; i < keys.length; i++) {
    record = record[keys[i]] || (i === keys.length - 1 ? defaultValue : {});
  }
  return record || defaultValue;
};

let filesNum = 0;
const filesArr: any[] = [];
//补0
function repair(i: number) {
  if (i >= 0 && i <= 9) {
    return '0' + i;
  } else {
    return i;
  }
}
// 格式化时间
function getCurrentTime(time: any, type: any): any {
  const date = new Date(time || ''); //当前时间
  const year = date.getFullYear(); //返回指定日期的年份
  const month = repair(date.getMonth() + 1); //月
  const day = repair(date.getDate()); //日
  const hour = repair(date.getHours()); //时
  const minute = repair(date.getMinutes()); //分
  const second = repair(date.getSeconds()); //秒
  const milliseconds = repair(date.getMilliseconds()); //毫秒

  //当前时间
  let curTime: string | number = '';
  switch (type) {
    case 'HH:mm:ss':
      curTime = hour + ':' + minute + ':' + second;
      break;
    case 'getmillisecond':
      curTime = new Date(time).getTime();
      break;
    case 'yyyy-MM-dd HH:mm:ss:SSS':
      curTime =
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hour +
        ':' +
        minute +
        ':' +
        second +
        ':' +
        milliseconds;
      break;

    default:
      curTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
      break;
  }

  return curTime;
}

//聊天消息发送人转义
function transferredMeaning(data: string, workgroupList: any[]) {
  //系统通知
  if (data == 'systemNotifyUser') {
    return '系统通知';
  }
  //访客
  else if (data.indexOf('visitor') != -1) {
    return data.replace('visitor', '访客');
  } else {
    if (workgroupList) {
      for (let i = 0; i < workgroupList.length; i++) {
        const item = workgroupList[i].users;
        for (let j = 0; j < item.length; j++) {
          if (data == item[j].username) {
            return item[j].nickname;
          }
        }
      }
    } else {
      return data;
    }
  }
}
//订阅地址前缀
function subscribePrefix(data: string) {
  let prefix = '';
  switch (data) {
    case 'user':
      prefix = '/topic/user.';
      return prefix;
    case 'subDomain':
      prefix = '/topic/subDomain.';
      return prefix;
    case 'contact':
      prefix = '/topic/contact.';
      return prefix;
    case 'workGroup':
      prefix = '/topic/workGroup.';
      return prefix;
    case 'visitor':
      prefix = '/topic/visitor.';
      return prefix;
  }
}

//url解码提取文件名
function urlDraw(url: string, name: string) {
  const rule = new RegExp(name + '=(\\S*)');
  const matches = url.match(rule);
  if (matches) {
    url = decodeURI(matches[1]);
  }
  return url;
}
//协助客服名字拆分
function assistCustomerService(data: string) {
  const name = data.split('_')[1];
  return name;
}

//根据消息类型 过滤提示音
function filterPromptSound(type: string) {
  const filterType = [
    'notification_customized',
    'notification_session',
    'notification_agent_close',
    'notification_visitor_close',
    'notification_session_visitor_remind',
    'notification_auto_close',
    'notification_preview',
    'notification_session_agent_remind'
  ];
  if (filterType.indexOf(type) != -1) {
    return false;
  } else {
    return true;
  }
}
//点击图片放大
function enlargeImg(data: string) {
  //新网页打开
  window.open(data);
}

//光标定位到div文本末尾处
function cursorMovesToEnd(el: any) {
  el.focus();
  if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') {
    const range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    const sel = window.getSelection();
    if (sel) {
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  // else if (typeof document.body.createTextRange != 'undefined') {
  //   const textRange = document.body.createTextRange();
  //   textRange.moveToElementText(el);
  //   textRange.collapse(false);
  //   textRange.select();
  // }
}

function getContentText(content: any) {
  let innerText = content;
  const emotions = innerText.match(/<img class="emotion-item".*?>/g);
  if (emotions && emotions.length) {
    emotions.forEach(function (emotion: any) {
      // let text = emotion.match(/\[.*?\]/g);
      const indexStr = emotion
        .match(/appkefu_f[0-9]{3}.png/g)[0]
        .replace('appkefu_f', '')
        .replace('.png', '');

      if (indexStr) {
        const index = parseInt(indexStr);
        const enKey: string = Object.keys(emotionData.emotionMap)[index - 1];
        const emoText = `[${emotionData.emotions[enKey]}]`;
        innerText = innerText.replace(emotion, emoText);
      }
    });
  }
  return innerText;
}

//获取等待时长
function getWaitTime(time: any) {
  //获取time距离当前时间的秒数
  let timeNum = (new Date().getTime() - new Date(time).getTime()) / 1000;
  // //保留整数部分
  // let intNum = Math.floor(timeNum)
  // //将秒数转换为分秒 小于10的显示为0x
  // let min = Math.floor(intNum / 60) < 10 ? '0' + Math.floor(intNum / 60) : Math.floor(intNum / 60)
  // let sec = Math.floor(intNum % 60) < 10 ? '0' + Math.floor(intNum % 60) : Math.floor(intNum % 60)
  setInterval(function () {
    timeNum++;
    const min =
      Math.floor(timeNum / 60) < 10 ? '0' + Math.floor(timeNum / 60) : Math.floor(timeNum / 60);
    const sec =
      Math.floor(timeNum % 60) < 10 ? '0' + Math.floor(timeNum % 60) : Math.floor(timeNum % 60);
    return min + ':' + sec;
  }, 1000);
}

/**
 * 复制
 * @param value
 */
const copyToClipboard = (
  content: string,
  clickEvent: any,
  message: any,
  successMsg: string,
  errorMsg: string
) => {
  const clipboard = new Clipboard(clickEvent.target, {
    text: () => content
  });

  clipboard.on('success', () => {
    message.success(successMsg);
    clipboard.destroy();
  });

  clipboard.on('error', (e) => {
    message.error(errorMsg);
    console.error('clipboard.ERROR', e);
    clipboard.destroy();
  });

  (clipboard as any).onClick(clickEvent);
};

/**
 * 从后往前查找匹配数组数据
 * @param array
 * @param condition
 * @returns
 */
function findLastIndex(array: any[], condition: (item: any) => boolean) {
  if (!Array.isArray(array) || typeof condition !== 'function') {
    console.error('Invalid arguments: array must be an array, and condition must be a function.');
    return -1;
  }

  for (let i = array.length - 1; i >= 0; i--) {
    if (condition(array[i])) {
      return i;
    }
  }
  return -1;
}

/**
 * 转换资源时间，mm:ss
 * @param milliseconds
 * @returns
 */
function formatMillisecondsToMMSS(milliseconds: number) {
  // 计算秒数
  let seconds = Math.floor(milliseconds / 1000);
  // 计算分钟数
  const minutes = Math.floor(seconds / 60);
  // 剩余的秒数
  seconds = seconds % 60;

  // 拼接成 mm:ss 格式
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

/**
 *是否是链接消息
 * @param content 内容
 */
function isLink(content: string): boolean {
  return /^(https?|ftp|file|rtsp|mms):\/\/[^\s]+$/.test(content);
}

function paste_img(e: any, isRobot: boolean) {
  const clipboardData = e.clipboardData || (window as any).clipboardData;
  let pasteSuccess = false;
  if (clipboardData.items) {
    const inputContent = document.getElementById('inputContent') as any;
    const ele = e.clipboardData.items;
    for (let i = 0; i < ele.length; ++i) {
      if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -1) {
        if (isRobot) {
          break;
        }
        pasteSuccess = true;
        const blob = ele[i].getAsFile();
        const reader = new FileReader();
        reader.onload = function (event) {
          const new_img = document.createElement('img');
          new_img.setAttribute('src', (event.target as any).result);
          new_img.setAttribute('id', `${filesNum}`);
          new_img.style.maxWidth = '70%';
          new_img.style.height = 'auto';
          inputContent.appendChild(new_img);
          filesArr[filesNum] = blob;
          filesNum++;
          cursorMovesToEnd(inputContent);
        };
        reader.readAsDataURL(blob);
      } else if (ele[i].kind == 'string' && ele[i].type.indexOf('text/plain') !== -1) {
        pasteSuccess = true;
        ele[i].getAsString(function (str: any) {
          inputContent.append(str);
          cursorMovesToEnd(inputContent);
        });
      }
    }
  } else {
    alert('请使用谷歌、火狐等浏览器!');
  }
  return pasteSuccess;
}

/**
 * 格式化语音时长
 * 例子1：10s  → （0:10）。
 * 例子2：2s →  （0:2）。
 * 例子3：65s → （1:05）。
 * 例子4：135s → （2:15）。
 */
const pad = (num:number) => num.toString().padStart(2, '0');
export function formatDuration(value:number) {
  const totalSeconds = Math.floor(value);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  if (hours > 0) {
    return `${hours}:${pad(minutes)}:${pad(seconds)}`;
  } else if (minutes > 0) {
    return `${minutes}:${pad(seconds)}`;
  } else {
    return `0:${pad(seconds)}`;
  }
}


//导出
export default {
  getCurrentTime,
  transferredMeaning,
  subscribePrefix,
  urlDraw,
  assistCustomerService,
  filterPromptSound,
  enlargeImg,
  cursorMovesToEnd,
  getContentText,
  getWaitTime,
  copyToClipboard,
  findLastIndex,
  formatMillisecondsToMMSS,
  isLink,
  filesArr,
  paste_img,
  formatDuration
};
